import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/Home.vue'
import store from "@/store"

Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    redirect: "home"
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/Goods',
    name: 'Goods',
    component: () => import('../views/Goods.vue')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/user.vue'),
    // 路由独享守卫
    // beforeEnter: (to, from, next) => {
    //   let token = localStorage.getItem("x-auth-token")
    //   if (token) {
    //     next();
    //   } else {
    //     store.dispatch("showToast/asyncChangeIsShowToastModal", {
    //       flag: true,
    //       toastMsg: '请先登录！',
    //       toastType: "warning"
    //     })
    //   }
    // }
    redirect: "/user/cart",
    children: [
      {
        path: "cart",
        component: () => import('../components/user/Cart.vue'),
      }
    ]
  },
  {
    path: '/free',
    name: 'free',
    component: () => import('../views/free.vue')
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('../views/order.vue')
  },
  {
    path: '/details',
    name: 'details',
    component: () => import('../views/Details.vue')
  },
  {
    path: "*",
    name: 'error',
    component: () => import('../components/Error.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 解决多次点击报错
// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
};

// 设置全局前置守卫
// router.beforeEach((to, from, next) => {
//   console.log(to, from);
//   if (to.path == "/user") {
//     let token = localStorage.getItem("x-auth-token")
//     if (token) {
//       next();
//     } else {
//       store.dispatch("showToast/asyncChangeIsShowToastModal", {
//         flag: true,
//         toastMsg: '请先登录！',
//         toastType: "warning"
//       })
//     }
//   } else {
//     next();
//   }
// })

export default router
